package com.ymh.service.impl;

import com.ymh.common.enums.StatusCodeEnum;
import com.ymh.common.exception.CustomException;
import com.ymh.dao.ProductDao;
import com.ymh.domain.ProductDO;
import com.ymh.domain.ProductDTO;
import com.ymh.service.ProductService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author: 13590
 * @date: 2020/10/27 20:13
 * @description:
 */
@Service
public class ProductServiceImpl implements ProductService {

  @Autowired
  private ProductDao productDao;

  @Override
  @Transactional(rollbackFor = CustomException.class)
  public void insertProduct(ProductDTO productDTO) {
    ProductDO productDO = new ProductDO();
    BeanUtils.copyProperties(productDTO, productDO);
    productDao.save(productDO);
  }

  @Override
  @Transactional(rollbackFor = CustomException.class)
  public void delete(String productCode) {
    productDao.delete(new ProductDO().setProductCode(productCode));
  }

  @Override
  @Transactional(rollbackFor = CustomException.class)
  public void update(ProductDTO productDTO) {
    ProductDO productDO = new ProductDO();
    BeanUtils.copyProperties(productDTO, productDO);
    productDao.save(productDO);
  }

  @Override
  public ProductDTO getByProductCode(String productCode) {
    ProductDTO productDTO = new ProductDTO();
    productDao
        .findOne(Example.of(new ProductDO().setProductCode(productCode))).ifPresent(
        productDO -> BeanUtils.copyProperties(productDO, productDTO));
    return productDTO;
  }

  @Override
  @Transactional(rollbackFor = CustomException.class)
  public void deduct(String productCode, Integer deductCount) {

    ProductDO productDO = productDao
        .findOne(Example.of(new ProductDO().setProductCode(productCode))).orElseThrow(() ->
            new CustomException(StatusCodeEnum.COMMON_EX_STATUS_CODE.getStatus(),
                "can't deduct product,product is null"));

    int surplus = productDO.getCount() - deductCount;
    if (surplus < 0) {
      throw new CustomException(StatusCodeEnum.COMMON_EX_STATUS_CODE.getStatus(),
          "can't deduct product,product's count is less than deduct count");
    }
    productDO.setCount(surplus);
    productDao.save(productDO);
  }
}
